<template>
  <div class="app-container" v-loading="loading" element-loading-background="rgba(0, 0, 0, 0.8)" element-loading-text="拼命加载服务中。。">
    <!-- <div style="font-size: 20px; margin-bottom: 50px; text-align: center">
      <span>CMSAutoCreate终端</span>
      <el-divider></el-divider>
      <span>{{ tipMessage }}</span>
    </div> -->
    <el-row class="header-nav"> 
      <el-col class="header-nav-left" :span="12">
        <img src="static/img/newLogo.png" />
        <!-- <div class="newLogo"></div> -->
      </el-col> 
      <el-col class="header-nav-right" :span="12">
        <span>CMSOutAuto终端</span>  
      </el-col>    
    </el-row>  

    <el-row class="main-section">
      <!-- 身份证信息 -->
      <el-col class="main-section-left-box" :span="16" :gutter="30">
        <div class="left-box-mession">
          预申报后自动刷卡取飞(交柜请提前验箱) 
        </div> 
        <div class="left-box-center"> 
          <img src="static/img/swipe.png" />
          <!-- <div class="swipe"></div> -->
        </div>
        <div class="left-box-center2"> 
          <img src="static/img/smile.png" />
          <!-- <div class="smile"></div> -->
          <div class="left-box-center2-mession">
          <!-- {{showMessage.mession}} -->
            <!-- 您的交柜未进行PAS申报(验箱的箱号未进行PAS申报)，请核查PAS申报资料  -->
            <span  v-bind:class="'color-' + showMessage.type">
            <!-- <span  class="color-green"> -->
              {{showMessage.msg}}
            </span>
          </div>  
        </div>
      </el-col> 
      <el-col class="main-section-right-box" :span="8">
        
        <!-- PCC卡信息 -->
        <div class="box-card right-box">
          <div slot="header" class="clearfix">
            <p>PCC卡信息</p>
          </div>
          <el-form ref="form" class="elForm" :model="form" label-width="80px">
            <el-form-item label="PCC卡号">
              <el-input v-model="form.permitNo" disabled></el-input>
            </el-form-item>

            <!-- <el-form-item label="车牌号">
              <el-input v-model="form.plate" disabled></el-input>
            </el-form-item> -->
          </el-form>
        </div>

        <div class="box-card right-box">
          <div slot="header" class="clearfix">
            <p>身份证信息</p>
          </div>
          <el-form ref="form"  class="elForm" :model="form" label-width="80px">
            <el-form-item label="姓名">
              <el-input v-model="form.saltName" disabled></el-input>
            </el-form-item>

            <el-form-item label="身份证号码">
              <el-input v-model="form.saltIdNo" disabled></el-input>
            </el-form-item>
          </el-form> 
        </div>
      </el-col>

      <el-col class="main-section-bottom-box" :span="24">
        <div class="bottom-box-title">
          <svg-icon iconClass="tips" style="margin:0 5%" />
            注意事项
          </div>
          <div class="bottom-box-tips"> 
            <!-- {{showMessage.tips}} -->
            请不要在飞仔未打印完毕时拉扯飞仔纸,以免导致卡纸
          </div>
      </el-col>
    </el-row> 
  </div>
</template>
<script>

import { ipcRenderer } from 'electron'
import axios from 'axios'
import {
  showSuccessMsg,
  showErrorMsg,
  showWarningMsg,
  showInfoMsg,
  showNotify,
  debugLog,
  log,
} from '@/utils/message'
import { getNetworkIp } from '@/utils/http'
import LandingPage from '../../../components/LandingPage.vue'

export default {
  components: {LandingPage},
  data() {
    return { 
      loading:　false,
      tipMessage: '',
      sendMqttMsgSeq: 0,
      readPauseTime: 10000,
      readIdCardThread: null,
      readIdCardThread: null,
      pauseReadIdCardThread: null,
      pauseReadIcCardThread: null,
      pauseReadCardThread: null,
      countdownThread: null,
      isReadIdCard: true,
      isReadIcCard: true,
      showMessage: {
        msg: '请刷卡......',
        success: false,
        type: 'success',
        mession:'您的交柜未进行PAS申报(验箱的箱号未进行PAS申报)，请核查PAS申报资料',
        tips: '请不要在飞仔未打印完毕时拉扯飞仔纸,以免导致卡纸'
      },
      form: {
        name: '',
        idNo: '',
        saltIdNo: '',
        saltName: '',
        pccId: '',
        permitNo: '',
      },
      appConfigData: null,
    }
  },
  created() {

    /*
    log(__filename)
    log(__dirname) */
    setTimeout(() => {
      this.startMqttConnect()
    }, 2000)
    setTimeout(() => {
      //  加载dll
      // this.loadCardDll()
      this.initReadThread()
    }, 6000)
  },
  mounted() { 
  },
  methods: {
    showMsg(msg, type) {
      this.showMessage.msg = msg
      this.showMessage.type = type
    },
    resetFormObject() {
      this.form = {
        name: '',
        idNo: '',
        pccId: '',
        saltIdNo: '',
        saltName: '',
        permitNo: '',
      }
    },
    // 开启读ID卡线程
    startReadIdCardThread() {
      this.stopReadIdCardThread()
      this.readIdCardThread = window.setInterval(() => {
        if (this.isReadIdCard) {
          ipcRenderer.send('read-id-card')
        }
      }, 1000)
    },
    //关闭读ID卡线程
    stopReadIdCardThread() {
      if (this.readIdCardThread) {
        window.clearInterval(this.readIdCardThread)
      }
      return true
    },
    // 开启读IC卡线程
    startReadIcCardThread() {
      this.stopReadIcCardThread()
      debugLog('开始读 read-ic-card', '读卡信息')
      this.readIcCardThread = window.setInterval(() => {
        if (this.isReadIcCard) {
          ipcRenderer.send('read-ic-card')
        }
      }, 1000)
    },
    //关闭读IC卡线程
    stopReadIcCardThread() {
      if (this.readIcCardThread) {
        window.clearInterval(this.readIcCardThread)
      }
      return true
    },
    // 暂停读身份证
    pauseReadIdCard() {
      this.isReadIdCard = false
      //清空倒计时
      this.clearCountdownThread()
      // 读卡成功后暂停  如果ic卡的状态也是暂停说明就可以提交了
      if (this.isReadIcCard) {
        this.readCardCountdown('请刷PCC卡')
      } else {
        this.showMsg('服务器正在验证卡信息')
        this.sendMqttMessage()
      }
    },
    pauseReadIcCard() {
      this.isReadIcCard = false
      //清空倒计时
      this.clearCountdownThread()

      if (this.isReadIdCard) {
        this.readCardCountdown('请刷身份证')
      } else {
        this.showMsg('服务器正在验证卡信息')
        this.sendMqttMessage()
      }
    },
    readCardCountdown(msg) {
      var count = 10
      this.clearCountdownThread()

      this.countdownThread = window.setInterval(() => {
        count--
        this.showMsg(
          msg + '......      超时倒计时 : ' + count + ' sec.'
        )
        if (count <= 1) {
          this.timeoutHandle()
        }
      }, 1000)
    },
    clearCountdownThread() {
      if (this.countdownThread) {
        window.clearInterval(this.countdownThread)
      }
    },
    timeoutHandle() {
      this.clearCountdownThread()
      this.showMsg('处理超时...')
      setTimeout(() => {
        this.resetReadThread()
      }, 1000)
    },
    //初始化读卡服务
    initReadThread() {
      this.stopReadThread()
      debugLog('初始化读卡服务', '读卡信息')
      //重启服务
      setTimeout(() => {
        this.loadCardDll()


      }, 2000)
    },
    resetReadThread() {
      //关闭暂停程序
      if (this.pauseReadIdCardThread) {
        window.clearTimeout(this.pauseReadIdCardThread)
      }
      if (this.pauseReadIcCardThread) {
        window.clearTimeout(this.pauseReadIcCardThread)
      }

      window.setTimeout(() => {
        this.isReadIdCard = true
        this.isReadIcCard = true
        this.resetShowMessage()
        this.resetFormObject()
        debugLog('恢复读卡服务')
      }, 10000)
    },
    //清空暂停线程
    stopReadThread() {
      //关闭暂停程序
      if (this.pauseReadIdCardThread) {
        window.clearTimeout(this.pauseReadIdCardThread)
      }
      if (this.pauseReadIcCardThread) {
        window.clearTimeout(this.pauseReadIcCardThread)
      }
      //停止读卡线程
      this.stopReadIdCardThread()
      this.stopReadIcCardThread()
      this.isReadIdCard = true
      this.isReadIcCard = true
      this.resetShowMessage()
      debugLog('关闭读卡服务')
      //重启服务
      /*     setTimeout(() => {
        this.loadCardDll()
      }, 2000) */
    },
    // 重置
    resetShowMessage() {
      log('=== resetShowMessage ===')
      this.showMessage = {
        msg: '请刷卡......',
        success: false,
        type: 'success',
      }
    },
    //  =====start===读卡操作=====
    // 初始化加载dll
    loadCardDll() {
      console.log('=loadCardDll')
      this.$message({
          message: '正在加载系统文件',
          type: 'info'
      })
      ipcRenderer.send('load-card-dll-thread')
      // ipcRenderer.send('load-test-dll-thread')

      ipcRenderer.on('load-card-dll-thread-reply', (event, res) => {
        log('load-card-dll-thread-reply')
        debugLog(res)
        this.registerReadListener()
        this.startReadIdCardThread()
        this.startReadIcCardThread()
        this.$message({
          message: '读卡服务启动成功',
          type: 'success'
        })
        debugLog('读卡服务启动成功')
      })
    },
    // 注册ID和IC卡消息监听器
    registerReadListener() {
      // 注册ID卡消息监听器
      ipcRenderer.on('read-id-card-reply', (event, res) => {
        // 返回读卡接口 -999 返回0能读取到信息  返回 2代表设备链接，但是找不到卡   返回1代表设备没有连接 因为有中文所以要转码  111
        if (this.isReadIdCard) {
          log('====read-id-card-reply====')
          log(res)
          let msgInfo = JSON.stringify(res)
          if (res.readCode === 0) {
            // 读卡成功
            debugLog('身份证读取成功')
            this.form.name = res.name
            this.form.idNo = res.idNo
            this.form.saltIdNo = res.saltIdNo
            this.form.saltName = res.saltName
            this.showMsg('身份证读取成功')
            //暂停读取ID卡线程
            window.setTimeout(() => {
              this.pauseReadIdCard()
            }, 1000)
            msgInfo += '====读卡成功'
          } else if (res.readCode === 2) {
            // this.showMsg('身份证无效', 'error')
            msgInfo += '====身份证无效'
          } else {
            log('身份证设备连接错误', 'warning')
            msgInfo += '====身份证设备连接错误'
            // this.showMsg('身份证设备连接错误', 'warning')
          }
          debugLog(msgInfo, '读卡信息')
        }
      })
      // 注册IC卡消息监听器
      ipcRenderer.on('read-ic-card-reply', (event, res) => {
        log('====read-ic-card-reply====')
        let msgInfo = JSON.stringify(res)
        log(msgInfo)
        if (res.readCode == 0) {
          this.form.pccId = res.cardNo
          this.form.permitNo = res.permitNo
          this.showMsg('PCC卡读取成功')
          window.setTimeout(() => {
            this.pauseReadIcCard()
          }, 1000)

          log('====PCC卡读取成功')
        } else if (res.readCode === 2) {
          log('PPC无效', 'error')
        } else {
          log('PC卡设备端口连接错误')
        }
      })
    },
    // =====end===读卡操作=====
    // =====start===MQTT=====
    deviceAuthenticate(queryObject) { 
      this.$message({
          message: '正在连接服务器',
          type: 'info'
      })
      log(queryObject)
      debugLog(queryObject.eipUr)
      axios
        .post(queryObject.eipUrl + '/api/deviceAuthenticate', queryObject, {
          timeout: 3000,
        })
        .then((res) => {
          // var resObj = JSON.parse(res)
          var ret = res.data
          log(ret)
          if (ret.result && ret.result === 'success') {
            log('===设备注册成功===')
            this.loading = false
            this.$message({
                message: '设备注册成功',
                type: 'success'
            })
            debugLog(ret, '设备注册')
            this.appConfigData.sessionId = ret.data.sessionId
            this.appConfigData.serviceInstanceIpAddress =
              ret.data.serviceInstanceIpAddress
            this.appConfigData.serviceInstanceMqttPort =
              ret.data.serviceInstanceMqttPort
            this.connectMqtt(this.appConfigData)
          } else {
            showErrorMsg(res)
          }
        })
        .catch((error) => {
          showErrorMsg(error)
        })
    },
    // 启动 MQTT服务器连接
    startMqttConnect() {
      // 只有认证通过loading 才会打开
      this.loading = true;
      this.closeMqttConnect()
      if (!this.appConfigData) {
        this.readAppConfig()
      }

      if (this.appConfigData) {
        setTimeout(() => {
          log('========appConfigData========')
          log(this.appConfigData)
          this.deviceAuthenticate(this.appConfigData)
          // var appConfigInfo = JSON.parse(this.appConfigDat)
          //验证读取本地配置文件  每次都
          // this.connectMqtt(this.appConfigData)
        }, 2000)
      }
    },
    connectMqtt(mqttObject) {
      log('startMqttConnect')
      debugLog(mqttObject, 'MQTT连接信息')
      ipcRenderer.send('start-mqtt-connect', mqttObject)

      ipcRenderer.on('start-mqtt-connect-reply', (event, res) => {
        log('====start-mqtt-connect-reply====')
        debugLog(res, 'MQTT链接结果')
      })
      //注册业务返回监听器
      ipcRenderer.on('send-mqtt-client-message-reply', (event, res) => {
        log('===send-mqtt-client-message-reply===')
        if ('客户端未连接' === res){ 
          this.startMqttConnect()
        }
        debugLog(res)
      })

      ipcRenderer.on('mqtt-server-message-topic', (event, res) => {
        log('===mqtt-server-message-topic===')
        log(res)
        this.handleMqttMessage(res)
      })
    },
    // 关闭 MQTT服务器
    closeMqttConnect() {
      log('closeMqttConnect')
      ipcRenderer.send('close-mqtt-connect')

      ipcRenderer.on('close-mqtt-connect-reply', (event, res) => {
        log('close-mqtt-connect-reply')
        log(res)
      })
    },
    // 发送MQTT消息
    sendMqttMessage() { 
      this.sendMqttMsgSeq += 1
      let message = {
        dt: {
          idInfo: {
            idNu: this.form.idNo ,
            name: this.form.name ,
          },
          nGenFullTractorNo: '',
          tcCode: this.form.permitNo ,
          ip: getNetworkIp(),
          cardId: this.form.pccId ,
        },
        ic: 'AutoGateOut',
        sn: this.appConfigData.deviceSerialNo ,
        id: this.sendMqttMsgSeq,
        en: false,
      }
      debugLog(message, '请求MQTT信息')
      ipcRenderer.send('send-mqtt-client-message', 'api/gate/out', message)
    },
    // MQTT后端业务返回消息处理方法
    handleMqttMessage(mqttMessage) {
      //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":1,"dt":["192764","zxc","","y|GD|BW8337|",""]}
      console.log('handleMqttMessage ---->', mqttMessage)
      if (mqttMessage) {
        var messageObject = JSON.parse(mqttMessage)
        debugLog(messageObject, '回传信息')
        if (messageObject.rc && messageObject.rc == 1) {
          if (messageObject.ic === 'AutoGateOut'){
            this.showMsg('作业处理成功', 'green')
          } 
        } else if (messageObject.rc) {
          //{"sn":"NGSA000001","id":1234567,"ic":"AutoCreate","en":false,"rc":26,"rm":"未知的读卡器错误"}
          this.showMsg(messageObject.rm, 'blue')
        } else {
          this.showMsg('未知错误，请联系管理员。')
        }
        this.resetReadThread()
      }
    },
    // =====end===MQTT=====

    // =====start===注册业务，也是测试用=====
    readAppConfig() {
      ipcRenderer.send('read-app-config', '读取本地文件的配置文件')
      ipcRenderer.on('read-app-config-reply', (event, res) => {
        log(res)
        this.appConfigData = JSON.parse(res.data)
        this.startMqttConnect()
      })
    },
  },
}
</script>

<style scoped>
.line {
  text-align: center;
}

.header-nav{
  width: 100%;
  height: 45px;
  padding:0 15px;
  background: linear-gradient(180deg, #F7FBFF 0%, #EBF0FF 100%);
  box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.5), inset 0px -1px 2px 0px #B0B9CE;
}
.header-nav>.header-nav-left{
  cursor:pointer; 
}
.header-nav>.header-nav-left>img{
   height:35px;
   margin-top:5px;
}
.header-nav>.header-nav-right{
  height:100%; 
  padding-top: 7.5px;
  /* display:flex; */
  text-align: right;
  align-items:center;
}
.header-nav>.header-nav-right>span{
  font-size: 17px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #213767;
  line-height: 26px;
  text-shadow: 0px 1px 0px rgba(255, 255, 255, 0.5);
}

.main-section{
  width:100%; 
  background:url('/static/img/bg.png');
  height:calc(100vh - 45px);
  overflow:hidden;
  background-size:100% 100%;
  background-repeat: no-repeat;
  padding:25px;
}

.main-section-right-box{
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 35%;
  height: 70%;
  float:right;
  padding:5%;
  flex-direction: column;
  display: flex;
  padding: 2%;
  justify-content: space-between;
}
 
.right-box{
  height:48%;
  width:100%
}

.right-box >>>.el-form-item__label{
  font-size: 12px;
}
.right-box .elForm {
  background:#fff; 
  width:100%;
  height:80%;
  border-radius: 5px;
  flex-direction: column;
  display: flex;
  padding-top:25px;
  padding-right:25px;
  overflow: hidden;
}
.right-box p{
  font-size: 13px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  font-size: 16px; 
  color: #e5e2e2; 
  line-height: 20px;
  margin:2%;
  text-shadow: 0px 1px 1px rgba(0, 0, 0, 0.5);
}

.main-section-left-box{
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 62%;
  height: 70%;
  float:left;
  display:flex;
  flex-direction: column;
  align-items:center;
  justify-content: space-evenly;
}

.left-box-mession{ 
  font-size: 12px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #FFFFFF;
  width: 100%;
  text-align: center;
  height: 18px;
}
.left-box-center{
  width:90%;
  height:40%;
  position: relative;
  background:url('/static/img/bg2.png');
  border-radius: 15px;
  background-size: 100% 100%;
}


.smile{
  width: 180px;
  height: 80%;
  margin: 10px;
  background:url('/static/img/smile.png') ;
  background-size: 130px 125px;
}

.swipe {
  /* width: 180px; */
  height: 80%;
  margin: 10px;
  margin-top: 60px;
  background:url('/static/img/swipe.png') no-repeat center ;
  background-size: 240px 140px;
}
.left-box-center2{
  width:90%;
  height:40%;
  position: relative;
  background:url('/static/img/bg3.png');
  border-radius: 15px;
  background-size: 100% 100%;
  display:flex;
  justify-content:center;
  align-items:center;
  padding: 0 5%;
}
.left-box-center2>img{
  height:50%;
  margin-right:5%;
}
.left-box-center2-mession{
  height:70%;
  width:100%;
  font-size: 21px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #196CC8;
  display: flex;
  align-items: center;
}
.left-box-center>img{
  position:absolute;
  width: 25%;
  left: 50%;
  top: 50%;
  transform: translate(-50%,-50%);
}

.main-section-bottom-box{
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
}
.bottom-box-title{
  background:#fff;
  width: 15%;
  height: 20%;
  display:flex;
  align-items: center;
  justify-content:center;
  font-size: 11px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #3D89E7;
  border-bottom-right-radius: 14px;
  border-bottom-left-radius: 14px;
}
.bottom-box-tips{
  height:100%;
  width:80%;
  display:flex;
  align-items: center;
  justify-content:center;
  font-size: 11px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #FFFFFF;
}

.main-section-bottom-box{
  background: rgba(255, 255, 255, 0.1);
  border-radius: 5px;
  border: 1px solid rgba(255, 255, 255, 0.2);
  width: 100%;
  margin-top:3%;
  height: 100px;
  font-size: 15px;
}

.bottom-box-title{
  background:#fff;
  width: 15%;
  height: 20%;
  display:flex;
  align-items: center;
  justify-content:center;
  font-size: 11px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #3D89E7;
  border-bottom-right-radius: 14px;
  border-bottom-left-radius: 14px;
}
.color-green{
  color: green;
}
.color-blue{
  color: blue;
}
.bottom-box-tips{
  height:100%;
  width:80%;
  display:flex;
  align-items: center;
  justify-content:center;
  font-size: 13px;
  font-family: SourceHanSansCN-Bold, SourceHanSansCN;
  font-weight: bold;
  color: #FFFFFF;
}
</style>
